package com.iqilu.ksd.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.activity.AddLiveActivity;
import com.iqilu.ksd.activity.AuthActivity;
import com.iqilu.ksd.activity.LiveActivity;
import com.iqilu.ksd.activity.LiveListActivity;
import com.iqilu.ksd.activity.LiveSearchActivity;
import com.iqilu.ksd.activity.LoginActivity;
import com.iqilu.ksd.adapter.LiveAdapter;
import com.iqilu.ksd.bean.LiveBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.UserRole;
import com.iqilu.ksd.event.ChangeUserInfoEvent;
import com.iqilu.ksd.utils.JSONUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Coofee on 2016/10/11.
 */

public class LiveFragment extends BaseFragment {

    private static final String TAG = "LiveFragment";

    private UserBean user;
    private int page;
    private LiveAdapter adapter;
    private ArrayList<LiveBean> list = new ArrayList<LiveBean>();

    private RelativeLayout layHead;
    private ImageView btLeft;
    private ImageView btRight;
    //    private ImageView btSearch;
    private TextView tvTitle;
    private XRefreshView xRefreshView;
    private RecyclerView rvList;
    private ImageView imgEmpty;
    private RelativeLayout layEmpty;
    private ImageView btReload;
    private RelativeLayout layLoading;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_common, null);
        layHead = getView(view, R.id.lay_head);
        btLeft = getView(view, R.id.bt_left);
        btRight = getView(view, R.id.bt_right);
//        btSearch = getView(view,R.id.bt_search);
        tvTitle = getView(view, R.id.tv_title);
        setZHTypeface(tvTitle);
        imgEmpty = getView(view, R.id.img_empty);
        layEmpty = getView(view, R.id.lay_empty);
        btReload = getView(view, R.id.bt_reload);
        layLoading = getView(view, R.id.lay_loading);
        xRefreshView = getView(view, R.id.xRefreshView);
        rvList = getView(view, R.id.rv_list);
        layLoading = getView(view, R.id.lay_loading);
        layLoading.setVisibility(View.VISIBLE);
        imgEmpty.setImageResource(R.drawable.bg_nolive);
        btReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page = 1;
                layLoading.setVisibility(View.VISIBLE);
                xRefreshView.setVisibility(View.VISIBLE);
                getList();
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);
        adapter = new LiveAdapter(context);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(context));
        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.enableReleaseToLoadMore(true);
        xRefreshView.enableRecyclerViewPullUp(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                getList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getList();
            }
        });
        rvList.setAdapter(adapter);
        adapter.setOnItemClickListener(new LiveAdapter.OnItemClickListener() {
            @Override
            public void OnItemClickListener(View view, int position) {
                Intent intent;
                LiveBean item = list.get(position);
                int mId = item.getId();
                int userId = item.getUid();
                String title = item.getTitle();
                String groupTitle = item.getGrouptitle();
                String album = item.getLitpic();
                String shareurl = item.getShareurl();
                if (item.getIsgroup() == 1) {
                    intent = new Intent(context, LiveListActivity.class);
                    intent.putExtra("title", groupTitle);
                    intent.putExtra("groupid", mId);
                } else {
                    intent = new Intent(context, LiveActivity.class);
                    intent.putExtra("title", title);
                    intent.putExtra("id", mId);
                    intent.putExtra("userid", userId);
                    intent.putExtra("album", album);
                    intent.putExtra("shareurl", shareurl);
                }
                startActivity(intent);
            }
        });
        initHead();
        page = 1;
        getList();
        return view;
    }

    private void initHead() {
        tvTitle.setText(getString(R.string.live_title));
        btRight.setImageResource(R.drawable.bt_search);
        btRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                context.startActivity(new Intent(context, LiveSearchActivity.class));
            }
        });
        btLeft.setImageResource(R.drawable.bt_add_live);
        btRight.setVisibility(View.VISIBLE);
        layHead.setVisibility(View.VISIBLE);
        btLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UserBean user = ((MyApplication) getActivity().getApplication()).getUser();
                if (user == null) {
                    startActivity(new Intent(context, LoginActivity.class));
                } else if (user.getRole() == UserRole.NORMAL) {
                    startActivity(new Intent(context, AuthActivity.class));
                } else {
                    startActivity(new Intent(context, AddLiveActivity.class));
                }
            }
        });
    }

    private void getList() {
        String url = Api.URL_LIVE + "?page=" + page;
        OkHttpUtils.get().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                afterRequest();
                if (page == 1) {
                    setEmpty();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                afterRequest();
                ArrayList<LiveBean> result = JSONUtils.requestList(response, "data", new TypeToken<ArrayList<LiveBean>>() {
                });
                if (page == 1) {
                    if (result == null || result.size() == 0) {
                        setEmpty();
                        Toast.makeText(context, R.string.list_empty, Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        list = result;
                    }
                } else {
                    if (result == null || result.size() == 0) {
                        Toast.makeText(context, R.string.list_not_have, Toast.LENGTH_SHORT).show();
                        return;
                    } else {
                        list.addAll(result);
                    }
                }
                adapter.setData(list);
                adapter.notifyDataSetChanged();
            }
        });
    }

    private void afterRequest() {
        layLoading.setVisibility(View.GONE);
        layEmpty.setVisibility(View.GONE);
        if (page == 1) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
        }
    }

    private void setEmpty() {
        adapter.setData(null);
        adapter.notifyDataSetChanged();
        layEmpty.setVisibility(View.VISIBLE);
        xRefreshView.setVisibility(View.GONE);
    }
}
